package com.project.slsx.activity;

import android.app.Dialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.project.slsx.Constant.Constans;
import com.project.slsx.R;
import com.project.slsx.bean.StorageTotalListBean;
import com.project.slsx.utils.GlideUtils;
import com.project.slsx.utils.ParamsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 入库总列表
 * 2019年4月4日 15:36:20
 */

public class StoreageTotalListActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = StoreageTotalListActivity.class.getSimpleName();
    private StorageTotalAdapter adapter;
    private SmartRefreshLayout sfl;
    private RecyclerView rv;
    private int page = 1;
    private TimePickerView startTime, endTime;
    private String start;
    private String end;
    private TextView tvStartTime;
    private TextView tvEndTime;

    @Override
    public int getLayoutId() {
        return R.layout.activity_storeage_total_list;
    }

    @Override
    public void initView() {
        findViewById(R.id.rl_back).setOnClickListener(v -> finish());
        TextView title = findViewById(R.id.tv_title);
        title.setText("入库总列表");
        findViewById(R.id.rl_calendar_from).setOnClickListener(this);
        findViewById(R.id.rl_calendar_to).setOnClickListener(this);
        findViewById(R.id.btn_storage_total_search).setOnClickListener(this);
        tvStartTime = findViewById(R.id.tv_starttime);
        tvEndTime = findViewById(R.id.tv_endtime);

        sfl = findViewById(R.id.smartrefreshlayout_storage_list_total);
        rv = findViewById(R.id.recyclerview_storage_list_total);
        rv.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new StorageTotalAdapter(R.layout.layout_item_storage_list_total);
        rv.setAdapter(adapter);

    }

    @Override
    public void initData() {
//        sfl.autoRefresh();
        showToast(mContext, "请选择查询时间段");
        sfl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                refresh(refreshLayout, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                refresh(refreshLayout, true);
            }
        });

        //初始化时间选择器
        initStartDate();
        initEndData();
    }

    private void initEndData() {
        Calendar instance = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 1);
        endTime = new TimePickerBuilder(this, (date, v) -> {
            end = getTime(date);
            tvEndTime.setText(end);
        })
                .setTimeSelectChangeListener(date -> Log.i("startTime", "onTimeSelectChanged"))
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(view -> Log.i("startTime", "onCancelClickListener"))
                .setRangDate(startDate, instance)
                .build();

        Dialog mDialog = endTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            endTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.1f);
            }
        }
    }

    private void refresh(RefreshLayout refreshLayout, boolean b) {
        refreshLayout.getLayout().postDelayed(() -> {
            if (b) {
                page = 1;
            } else {
                ++page;
            }
            getStorageListTotal(page, b);
        }, 50);
    }

    private void initStartDate() {
        Calendar instance = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 1);
        startTime = new TimePickerBuilder(this, (date, v) -> {
            start = getTime(date);
            tvStartTime.setText(start);
        })
                .setTimeSelectChangeListener(date -> Log.i("startTime", "onTimeSelectChanged"))
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(view -> Log.i("startTime", "onCancelClickListener"))
                .setRangDate(startDate, instance)
                .build();

        Dialog mDialog = startTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            startTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.1f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String resultTimeStr = format.format(date);
        String substring = resultTimeStr.substring(0, 10);
        return substring;
    }

    private void getStorageListTotal(int page, boolean b) {
        HttpParams storagealllistParams = ParamsUtils.getStoragealllistParams();
        storagealllistParams.put("page", page);
        storagealllistParams.put("starttime", start);
        storagealllistParams.put("endtime", end);
        OkGo.<String>post(Constans.BASEURL).tag("storagealllist").params(storagealllistParams).execute(new StringCallback() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (b) {
                    sfl.finishRefresh();
                } else {
                    sfl.finishLoadMore();
                }
            }

            @Override
            public void onSuccess(Response<String> response) {
                Log.i(TAG, "onSuccess: " + response.body());
                StorageTotalListBean storageTotalListBean = JSONObject.parseObject(response.body(), StorageTotalListBean.class);
                if (storageTotalListBean.getErrno() == Constans.SUCCESS) {
                    if (storageTotalListBean.getResult() != null && storageTotalListBean.getResult().size() > 0) {
                        List<StorageTotalListBean.ResultBean> result = storageTotalListBean.getResult();
                        if (b) {
                            adapter.setNewData(result);
                        } else {
                            adapter.addData(result);
                        }
                    } else {
                        showToast(mContext, "暂无数据");
                    }
                } else {
                    showToast(mContext, "网络错误");
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.rl_calendar_from:
                startTime.show(v);
                break;
            case R.id.rl_calendar_to:
                endTime.show(v);
                break;

            case R.id.btn_storage_total_search:
                if (TextUtils.isEmpty(start)) {
                    showToast(mContext, "请选择开始时间");
                    return;
                }
                if (TextUtils.isEmpty(end)) {
                    showToast(mContext, "请选择结束时间");
                    return;
                }
                sfl.autoRefresh();
                break;

        }
    }

    private class StorageTotalAdapter extends BaseQuickAdapter<StorageTotalListBean.ResultBean,
            BaseViewHolder> {

        public StorageTotalAdapter(int layoutId) {
            super(layoutId);
        }

        @Override
        protected void convert(BaseViewHolder holder, StorageTotalListBean.ResultBean item) {

            RequestOptions option = GlideUtils.getOption();
            ImageView thumb = holder.getView(R.id.iv_storage_thumb);
            Glide.with(mContext)
                    .load(item.getThumb())
                    .apply(option)
                    .into(thumb);
            holder.setText(R.id.tv_storage_total_name, item.getName());
            holder.setText(R.id.tv_storage_total_number, item.getNumber());
            holder.setText(R.id.tv_storage_total_cost_price, item.getCost_price());
            holder.setText(R.id.tv_storage_total_amount, String.valueOf(item.getAmount()));
            holder.setText(R.id.tv_storage_total_supplier, item.getSupplier_name());
            holder.setText(R.id.tv_storage_total_time, item.getCtime());
            holder.setText(R.id.tv_storage_total_gift, Double.valueOf(item.getCost_price()) == 0 ? "是" : "否");
        }
    }
}
